{extend name="common/base" /}
{block name="body"} 
<main>
    <div class="container">
        <div class="layui-tab shopping-cart-goods top-tab">
            <ul class="layui-tab-title">
                <li><a href="collect.html">My Collection</a></li>
                <li class="layui-this"><a href="shopping-cart.html">Shopping Cart</a></li>
            </ul>
            <ul class="layui-row layui-col-space25 shopping-cart-list">
                {volist name="list" id="cart"} 
                <li class="layui-col-md12 layui-col-xs12 shopping-cart-item" data-id="{$cart.id}" data-price="{$cart.specs.price_selling}" data-quantity="{$cart.number|default=1}">
                    <div class="layui-row">
                        <div class="cart-item-left layui-col-md3 layui-col-xs12">
                            <img src="{$cart.goods.cover}" alt="">
                        </div>
                        <div class="cart-item-middle layui-col-md6 layui-col-xs12">
                            <h1><a href="/goods/{$cart.goods.code}">{$cart.goods.name}</a> </h1>
                            <h2>$<span class="item-price">{$cart.goods.price_selling}</span></h2>
                            <div class="goods-size">
                                <span class="bg-button">{$cart.spec['尺码']}</span>
                                <span class="bg-button">{$cart.spec['颜色']}</span>
                                <span class="bg-button quantity-control">
                                    <img class="cart-reduce" data-id="{$cart.id}" data-quantity="{$cart.number|default=1}" data-price="{$cart.goods.price_selling}"  src="__ROOT__/static/images/shopping-cart-reduce.png" alt="Reduce">
                                    <span class="cart-number">{$cart.number|default=1}</span>
                                    <img class="cart-add" data-id="{$cart.id}" data-quantity="{$cart.number|default=1}" data-price="{$cart.goods.price_selling}" src="__ROOT__/static/images/shopping-cart-add.png" alt="Add">
                                </span>
                            </div>
                        </div>
                        <div class="cart-item-right layui-col-md3 layui-col-xs12">
                            <div class="layui-form">
                                <!-- 添加 lay-filter 属性 -->
                                <input class="checkbox-style select-item" lay-filter="cartCheckbox" type="checkbox" name="selectItem" checked>
                            </div>
                            <div class="order-directly">
                                <a class="color-button" href="/order/{$cart.id}">Order directly</a>
                                <div>
                                    {if $cart.is_collect} 
                                        <img src="__ROOT__/static/images/cancel-heart.png" alt="">
                                        <span  class="collect" data-code="{$cart.gcode}">Cancel</span>
                                    {else /} 
                                        <img src="__ROOT__/static/images/heart-empty.png" alt="">
                                        <span class="collect" data-code="{$cart.gcode}">Collect</span>
                                    {/if}
                                    <!-- <span class="cancel-item"><img src="__ROOT__/static/images/heart-empty.png" alt="">Cancel</span> -->
                                    <span class="delete-item"><img src="__ROOT__/static/images/delete.png" alt="">Delete</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </li>
                {/volist}
            </ul>
            <div class="total-price">
                <span class="price-font"><span class="selected-count">0</span> items have been selected</span>
                <span class="price-number">Total: $<span class="total-amount">0.00</span></span>
                <span class="color-button confirm-payment"><a href="javascript:void(0);">Confirm Payment</a></span>
            </div>
        </div>
    </div>
</main>


{/block}
{block name="js"} 
    <script>
        $(document).ready(function () {
            $(document).on('click', '.collect', function() {
                var that  = $(this);
                var code = $(this).data('code');
                var data = { gcode: code };
                // Make the AJAX request
                ajaxRequest('/collect', data, 'POST', this, function (response) {
                    
                    // Assuming the response will indicate if the item was successfully collected
                    if (response.code == 1) {
                        // Toggle image and text
                        var span = that;
                        var img = that.siblings('img');
                       
                        
                        // Check if currently collected (e.g., based on image or state)
                        if (span.text() === 'Collect') {
                            alert('dawda')
                            // Change to "cancel" state
                            img.attr('src', '__ROOT__/static/images/cancel-heart.png');
                            span.text('Cancel');
                        } else {
                            // Change to "collect" state
                            img.attr('src', '__ROOT__/static/images/heart-empty.png');
                            span.text('Collect');
                        }
                        
                        // Optional success message
                        layer.msg('SUCCESS', {icon: 1, time: 2000});
                    }
                });
            });
            // 初始化 layui 表单组件
            layui.use(['form'], function () {
                const form = layui.form;

                // 全选/取消全选
                form.on('checkbox(selectAll)', function (data) {
                    // 如果全选框被选中
                    const isChecked = data.elem.checked;
                    $('.select-item').prop('checked', isChecked);
                    form.render('checkbox'); // 重新渲染 checkbox
                    updateSummary(); // 全选时立即更新总金额和数量
                });

                // 单个商品的选择框变化
                form.on('checkbox(cartCheckbox)', function (data) {
                    // 检查所有复选框是否都已选择
                    const allChecked = $('.select-item').length === $('.select-item:checked').length;
                    $('.select-all').prop('checked', allChecked);
                    form.render('checkbox'); // 重新渲染 checkbox
                    updateSummary(); // 选择变化时更新总金额和数量
                });

                // 页面加载时默认更新
                updateSummary(); // 页面加载后，初始化时调用一次
            });

            // 更新总价和数量
            function updateSummary() {
                let totalAmount = 0;
                let selectedCount = 0;

                // 遍历每个购物车项，计算总金额和数量
                $('.shopping-cart-item').each(function () {
                    const $item = $(this);
                    const isSelected = $item.find('.select-item').prop('checked');
                    const price = parseFloat($item.data('price'));
                    const quantity = parseInt($item.data('quantity'));

                    if (isSelected) {
                        totalAmount += price * quantity;
                        selectedCount += quantity;
                    }
                });
                    
                // 更新显示的已选择数量和总金额
                $('.selected-count').text(selectedCount);
                $('.total-amount').text(totalAmount.toFixed(2));
            }

            // 监听数量变化
            $('.cart-add').off('click').on('click', function () {
                const $item = $(this).closest('.shopping-cart-item');
                const cartId = $item.data('id');
                const $quantity = $item.find('.cart-number');
                let quantity = parseInt($quantity.text());

                quantity++; // 每次点击增加 1
                $quantity.text(quantity); // 更新显示数量
                $item.data('quantity', quantity); // 更新购物车数据

                updateSummary(); // 更新总金额和数量
                syncCartData(cartId, quantity); // 同步购物车数据到后端
            });

            // 数量减少
            $('.cart-reduce').off('click').on('click', function () {
                const $item = $(this).closest('.shopping-cart-item');
                const cartId = $item.data('id');
                const $quantity = $item.find('.cart-number');
                let quantity = parseInt($quantity.text());

                if (quantity > 1) { // 确保数量不小于 1
                    quantity--; // 每次点击减少 1
                    $quantity.text(quantity); // 更新显示数量
                    $item.data('quantity', quantity); // 更新购物车数据

                    updateSummary(); // 更新总金额和数量
                    syncCartData(cartId, quantity); // 同步购物车数据到后端
                } else {
                    layer.msg('Quantity cannot be less than 1', { icon: 0, time: 1500 }); // 提示用户
                }
            });

            // 同步购物车数据到后端
            function syncCartData(cartId, quantity) {
                const data = { cartId, quantity };
                ajaxRequest('/update-cart', data, 'POST', this, function (response) {
                    layer.msg('Update success', { icon: 1, time: 2000 });
                });
            }

            // 删除购物车商品
            $('.delete-item').on('click', function () {
                const $item = $(this).closest('.shopping-cart-item');
                const cartId = $item.data('id');

                layer.confirm('Are you sure you want to delete this item?', { icon: 3, title: 'Confirm' }, function (index) {
                    deleteCartItem(cartId); // 删除购物车项
                    $item.remove();
                    updateSummary(); // 删除后更新总金额和数量
                    layer.close(index);
                });
            });

            // 删除购物车商品
            function deleteCartItem(cartId) {
                const data = { cartId };
                ajaxRequest('/delete-cart', data, 'POST', this, function (response) {
                    layer.msg('Delete success', { icon: 1, time: 2000 });
                  
                });
            }
        });

        $('.confirm-payment').on('click', function () {
                // 获取选中的购物车项 ID
                const selectedCartIds = [];
                $('.shopping-cart-item').each(function () {
                    const $item = $(this);
                    const isSelected = $item.find('.select-item').prop('checked');
                    if (isSelected) {
                        selectedCartIds.push($item.data('id'));
                    }
                });

                if (selectedCartIds.length === 0) {
                    layer.msg('Please select at least one item to order', { icon: 2, time: 2000 });
                    return;
                }

                // 构造跳转 URL
                const url = `/order/${selectedCartIds.join('_')}`;
                
                // 跳转到订单确认页面
                window.location.href = url;
            });

    </script>
{/block}